package com.nd.android.musicboxlibrary.interf.impl;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.common.StarAppConfig;
import com.google.gson.Gson;
import com.nd.android.musicboxlibrary.business.bean.FileInfo;
import com.nd.android.musicboxlibrary.business.bean.MusicInfo;
import com.nd.android.musicboxlibrary.business.comm.ApiManager;
import com.nd.android.musicboxlibrary.interf.IDownloadManager;
import com.nd.android.musicboxlibrary.interf.ManagerFactory;
import com.nd.android.musicboxlibrary.ui.vip.VipUtil;
import com.ngds.library.downloadcenter.AppDownloadHelper;
import com.ngds.library.downloadcenter.AppDownloadHelperImpl;
import com.product.android.utils.LogUtils;

import java.io.File;
import java.util.List;

/**
 * 下载相关接口
 * <br>
 * Created 2014年7月11日 下午10:56:11
 * 
 * @author 慕容秋(muroqiu@qq.com)
 * @see
 */
public class DownLoadManager implements IDownloadManager {

	private AppDownloadHelper mAppDownloadHelper;
	private Context mContext;

	/**
	 * Creates a new instance of DownLoadManager. <br>
	 * Created 2014年9月15日 下午11:15:30
	 * @param context Context
	 */
	public DownLoadManager(Context context) {
		mContext = context;
		mAppDownloadHelper = AppDownloadHelperImpl.getInstance(mContext);

		new Thread(new Runnable() {
			@Override
			public void run() {
				mAppDownloadHelper.start();
			}
		}).start();
	}

	/**
	 * 将音乐加入下载列表
	 * <br>
	 * Created 2014年9月15日 下午11:18:12
	 *
	 * @param musicInfo 音乐信息
	 * @author wat.ztag
	 */
	@Override
	public void addMusic2DownloadList(MusicInfo musicInfo , boolean isHQ) {
		try {
			if(!StarAppConfig.getBooleanConfig(StarAppConfig.CONFIG_VERSION1_8)){// by jiangwb
				if (musicInfo.isDownLoaded() || musicInfo.isDownLoading()) {
					// 正在下载，或者已下载成功的，跳过；
					return;
				}
			}
			LogUtils.d("DownLoadManager.java -- jiangwb", "addMusic2DownloadList -- 开始下载");
			musicInfo.setDownLoading(true);
			musicInfo.setDownLoaded(false);

			String musicUrl =  "";
			String musicName = "";
			ApiManager.getInstance(mContext).getDb().addMusic2DownloadList(musicInfo.getId() , isHQ);// by jiangwb 2014-11-26 11:14
			if(isHQ && musicInfo.getHQId() > 0){// by jiangwb 2014-11-20 11:21
				musicUrl =  musicInfo.getHQMusicUrl();// by jiangwb 2014-11-18 11:14
				musicName = musicInfo.getMusicName() + FileInfo.EXT_HQ_TEMP ;// by jiangwb 2014-11-20 10:14
			}else{
				musicUrl =  musicInfo.getMusicUrl();// by jiangwb 2014-11-18 11:20
				musicName = musicInfo.getMusicName() + FileInfo.EXT_TEMP ;// by jiangwb 2014-11-20 10:14
			}

			String description_Exits = mAppDownloadHelper.getDescription(mContext,musicUrl);
			if (!TextUtils.isEmpty(description_Exits)) {
				// 存在历史数据，先删除，防止下载异常;
				FileInfo fileInfo_Exits = new Gson().fromJson(description_Exits, FileInfo.class);
				if (fileInfo_Exits != null && fileInfo_Exits.getDownLoadId() > 0) {
					mAppDownloadHelper.deleteDownload(fileInfo_Exits.getDownLoadId());
				}
			}

			long downLoadId = mAppDownloadHelper.createAndStartDownload(mContext,
					musicUrl, FileInfo.DIR_LOCAL_MP3, musicName);
			FileInfo fileInfo = new FileInfo();
			if(isHQ&& musicInfo.getHQId() > 0){// by jiangwb 2014-11-26 14:21
				fileInfo.setType(FileInfo.TYPE_HQ_MUSIC);
			}else {                                                                       // by jiangwb 2014-11-26 14:21
				fileInfo.setType(FileInfo.TYPE_MUSIC);
			}                                                                               // by jiangwb 2014-11-26 14:21
			fileInfo.setHQId(musicInfo.getHQId());		 		      // by jiangwb 2014-11-26 14:21
			fileInfo.setId(musicInfo.getId());	                     // by jiangwb 2014-11-26 14:21	
			fileInfo.setDownLoadId(downLoadId);
			fileInfo.setName(musicInfo.getMusicName());
			String description = new Gson().toJson(fileInfo).toString();
			mAppDownloadHelper.setDescription(mContext, description,musicUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将音乐批量加入下载列表
	 * <br>
	 * Created 2014年9月15日 下午11:18:15
	 *
	 * @param musicInfoList 音乐列表
	 * @author wat.ztag
	 */
	@Override
	public void batchAddMusic2DownloadList(final List<MusicInfo> musicInfoList) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (musicInfoList == null || musicInfoList.isEmpty()) {
					return;
				}
				int size = musicInfoList.size();
				for (int i = 0; i < size; i++) {
					MusicInfo musicInfo = musicInfoList.get(i);
					if(musicInfo != null){
						addMusic2DownloadList(musicInfo, musicInfo.isHQ());
					}
				}
			}
		}).start();
	}

	/**
	 * 标识音乐下载完成
	 * <br>
	 * Created 2014年9月15日 下午11:18:17
	 *
	 * @param musicInfo 音乐信息
	 * @author wat.ztag
	 */
	@Override
	public void setMusicDownloaded(MusicInfo musicInfo) {
		ApiManager.getInstance(mContext).getDb().setMusicDownLoaded(musicInfo);
	}

	/**
	 * 将Lrc加入下载列表
	 * <br>
	 * Created 2014年9月15日 下午11:17:56
	 *
	 * @param musicInfo 音乐信息
	 * @author wat.ztag
	 */
	@Override
	public void addLrc2DownloadList(MusicInfo musicInfo) {
		try {
			String description_Exits = mAppDownloadHelper.getDescription(mContext,
					musicInfo.getLrcUrl());
			if (!TextUtils.isEmpty(description_Exits)) {
				// 存在历史数据，先删除，防止下载异常;
				FileInfo fileInfo_Exits = new Gson().fromJson(description_Exits, FileInfo.class);
				if (fileInfo_Exits != null && fileInfo_Exits.getDownLoadId() > 0) {
					mAppDownloadHelper.deleteDownload(fileInfo_Exits.getDownLoadId());
				}
			}

			long downLoadId = mAppDownloadHelper.createAndStartDownload(mContext,
					musicInfo.getLrcUrl(), FileInfo.DIR_LOCAL_LRC, musicInfo.getMusicName()
					+ FileInfo.EXT_LRC);
			FileInfo fileInfo = new FileInfo();
			fileInfo.setType(FileInfo.TYPE_LRC);
			fileInfo.setId(musicInfo.getId());
			fileInfo.setHQId(musicInfo.getHQId());
			fileInfo.setDownLoadId(downLoadId);
			String description = new Gson().toJson(fileInfo).toString();
			mAppDownloadHelper
			.setDescription(mContext, description, musicInfo.getLrcUrl());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将Lrc批量加入下载列表
	 * <br>
	 * Created 2014年9月15日 下午11:18:00
	 *
	 * @param musicInfoList 音乐列表
	 * @author wat.ztag
	 */
	@Override
	public void batchAddLrc2DownloadList(final List<MusicInfo> musicInfoList) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (musicInfoList == null || musicInfoList.isEmpty()) {
					return;
				}
				int size = musicInfoList.size();
				for (int i = 0; i < size; i++) {
					addLrc2DownloadList(musicInfoList.get(i));
				}
			}
		}).start();
	}

	/**
	 * 下载 未下载的喜欢歌曲
	 * <br>
	 * Created 2014年9月15日 下午11:18:03
	 *
	 * @author wat.ztag
	 */
	@Override
	public void addFavMusic2DownLoadList() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<MusicInfo> musicInfoList = ApiManager.getInstance(mContext).getDb().getMusicListOfFavForDownLoad();
				if (musicInfoList == null || musicInfoList.isEmpty()) {
					return;
				}
				int size = musicInfoList.size();
				for (int i = 0; i < size; i++) {
					MusicInfo musicInfo = musicInfoList.get(i);
					if(VipUtil.isVip() && musicInfo.getHQId() > 0){
						//by jiangwb 如果是vip用户，同时歌曲有HQ版本，就自动下载HQ文件
						musicInfo.setHQ(true);
					}
					addMusic2DownloadList(musicInfo , musicInfo.isHQ());
				}
			}
		}).start();
	}

	/**
	 * 结束下载 未下载的喜欢歌曲
	 * <br>
	 * Created 2014年9月15日 下午11:18:05
	 *
	 * @author wat.ztag
	 */
	@Override
	public void removeFavMusicFromDownLoadList() {
		// 已在下载队列了，不做处理
	}

	/**
	 * 删除下载音乐
	 * <br>
	 * Created 2014年9月15日 下午11:18:08
	 *
	 * @param musicInfo 音乐信息
	 * @author wat.ztag
	 */
	@SuppressLint("NewApi")
	@Override
	public void removeMusicFromDownloadList(MusicInfo musicInfo) {
		try {
			if(musicInfo == null){
				return ;
			}
			musicInfo.setDownLoaded(false);
			musicInfo.setDownLoading(false);
			ApiManager.getInstance(mContext).getDb().removeMusicFromDownloadList(musicInfo.getId());
			//ApiManager.getInstance(mContext).getDb().removeMusicFromDownloadList(musicInfo.getHQId());// by jiangwb
			ManagerFactory.getPlayerInstance().initMusicList(mContext);
			String description_Exits = "";// by jiangwb
			for(int i = 0 ; i < 2 ; i++){
				String url = "";
				if( i == 0 ){
					description_Exits = mAppDownloadHelper.getDescription(mContext,
							url = musicInfo.getMusicUrl());// by jiangwb
				}else if(i == 1){
					description_Exits = mAppDownloadHelper.getDescription(mContext,
							url = musicInfo.getHQMusicUrl());// by jiangwb
				}else{
					break;
				}

				if (!TextUtils.isEmpty(description_Exits)) {
					FileInfo fileInfo_Exits = new Gson().fromJson(description_Exits, FileInfo.class);
					if (fileInfo_Exits != null && fileInfo_Exits.getDownLoadId() > 0) {
						mAppDownloadHelper.deleteDownload(fileInfo_Exits.getDownLoadId());
						Intent intent = new Intent(AppDownloadHelper.ACTION_DOWNLOAD_DELETE);
			            intent.setPackage(mContext.getPackageName());
			            intent.putExtra(AppDownloadHelper.EXTRA_FILE_ID, fileInfo_Exits.getId());
			            intent.putExtra(AppDownloadHelper.EXTRA_FILE_TYPE, fileInfo_Exits.getType());
			            mContext.sendBroadcast(intent);
					}
				}

			}
			try {
				new File(musicInfo.getMusicPath()).delete();
				new File(musicInfo.getHQMusicPath()).delete();
				new File(musicInfo.getMusicTemp()).delete();
				new File(musicInfo.getHQMusicTemp()).delete();
			} catch (Exception e) {
				LogUtils.e("DownLoadManager.java -- jiangwb", "removeMusicFromDownloadList() \n " + e.toString());
			}
		
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
